#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
#include <stdio.h>

sig_atomic_t child_exit_status;

#define MSEC_PER_SECOND 1000000

void clean_up_child_process(int signal_number)
{
	int status;
	wait(&status);
	child_exit_status = status;
	printf("a child process is exit!\n");
	return ;
}

int main(int argc, char **argv)
{
	struct sigaction sigchild_action;
	memset((void*)&sigchild_action, 0, sizeof(struct sigaction));
	sigchild_action.sa_handler = clean_up_child_process;
	sigaction(SIGCHLD, &sigchild_action, NULL);

	int i = 10;
	while(i>0)
	{
		pid_t child_pid = fork();
		if(child_pid==0)
		{
			sleep(i);
			exit(0);
		}
		printf("i:%d\n", i);
		i--;
	}

	int ret = 0;
	struct timespec sleep_time;
	sleep_time.tv_sec = 20;
	sleep_time.tv_nsec = 0;
	while(1)
	{
		ret = nanosleep(&sleep_time, &sleep_time);
		if(ret!=-1)
			break;
		else
		{
			ret = nanosleep(&sleep_time, &sleep_time);
			printf("remain time:sec:%d\tmsec:%d\n", sleep_time.tv_sec, sleep_time.tv_nsec);
		}
	}
	
	return 0;
}
